<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card style="margin-top: 10px">
      <el-row>
        <el-col>
          <!-- 警告 -->
          <el-alert
            :closable="false"
            show-icon
            title="注意:只允许为第三季分类设置相关参数"
            type="warning"
          ></el-alert>
        </el-col>
      </el-row>
      <el-row style="margin-top: 15px">
        <el-col :span="10">
          <span>请选择商品分类:</span>
          <!-- 级联选择器 -->
          <el-cascader
            style="margin-left: 10px"
            v-model="cateValue"
            :options="cateList"
            :props="cateListProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isButtonVisible"
            @click="addDialog"
            >添加参数</el-button
          >
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isButtonVisible"
            @click="addDialog"
            >添加属性</el-button
          >
        </el-tab-pane>
      </el-tabs>
      <!-- 动态参数表格 -->
      <el-table
        :data="dyParams"
        style="width: 100%"
        border
        v-if="activeName === 'many'"
      >
        <el-table-column type="expand" width="100px">
          <!-- 通过作用插槽改变的所以要绑定才能渲染出 -->
          <template v-slot="scope">
            <!-- 渲染tag -->
            <el-tag
              closable
              @close="deleteParamsItem(index, scope.row)"
              v-for="(item, index) in scope.row.attr_vals"
              :key="index"
              >{{ item }}</el-tag
            >
            <!-- 按钮文本框切换 -->
            <el-input
              class="input-new-tag"
              v-if="scope.row.inputVisible"
              v-model="scope.row.inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm(scope.row)"
              @blur="handleInputConfirm(scope.row)"
            >
            </el-input>
            <!-- 绑定自己的数据 -->
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(scope.row)"
              >+ New Tag</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="#" type="index" width="180"> </el-table-column>
        <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editAdddyParmasForm(scope.row.attr_id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="editDeleteDyForm(scope.row.attr_id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 静态属性表格 -->
      <el-table
        :data="staticParmas"
        style="width: 100%"
        border
        v-if="activeName === 'only'"
      >
        <template v-slot="scope">
          <el-table-column type="expand" width="100px">
            <el-tag
              closable
              @close="deleteParamsItem(index, scope.row)"
              v-for="(item, index) in scope.row.attr_vals"
              :key="index"
              >{{ item }}</el-tag
            >
            <el-input
              class="input-new-tag"
              v-if="scope.row.inputVisible"
              v-model="scope.row.inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm(scope.row)"
              @blur="handleInputConfirm(scope.row)"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(scope.row)"
              >+ New Tag</el-button
            >
          </el-table-column>
        </template>
        <el-table-column label="#" type="index" width="180"> </el-table-column>
        <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editAddStaticForm(scope.row.attr_id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="editDeleteStaticForm(scope.row.attr_id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加属性对话框 -->
      <el-dialog
        :title="'添加' + isDoalog"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="closeAddDialog"
      >
        <el-form ref="addFormRef" :model="addForm" label-width="80px">
          <el-form-item :label="isDoalog">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAddForm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改属性对话框 -->
      <el-dialog
        :title="'修改' + isDoalog"
        :visible.sync="editDialogVisible"
        width="30%"
      >
        <el-form ref="editFormRef" :model="editForm" label-width="80px">
          <el-form-item :label="isDoalog">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 获取分类数据
      cateList: [],
      // 分类数据的配置
      cateListProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联选择器选中的数据
      cateValue: [],
      // 绑定激活标签页的名字
      activeName: 'many',
      // 添加动态参数
      dyParams: [],
      // 静态参数
      staticParmas: [],
      // 是否增加静态属性/添加动态参数对话框
      addDialogVisible: false,
      // 添加静态属性/动态参数的数据
      addForm: {},
      // 是否显示修改静态属性/动态参数的对话框
      editDialogVisible: false,
      // 是否修改静态属性/动态参数的数据
      editForm: {},
      // 修改参数的id
      editId: '',
      // 参数下可选项
      attrVals: []

    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('请求失败')
      }
      this.cateList = res.data
    },
    // 监听级别选择器数据改变
    handleChange () {
      this.listenActiveName()
      this.getCateList()
    },
    // 根据级联选择器id获取数据
    async listenActiveName () {
      if (this.cateValue.length === 3) {
        console.log(this.cateValue)
      } else {
        // 如果不是三级分类就要清空表格
        this.cateValue = []
        this.dyParams = []
        this.staticParmas = []
        return this.$message.error('要选择三级分类')
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateValue[this.cateValue.length - 1]}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      res.data.forEach((element) => {
        element.attr_vals = element.attr_vals
          ? element.attr_vals.split(' ')
          : []
        // 按钮输入框显示
        element.inputVisible = false
        // 按钮输入框的数据
        element.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.dyParams = res.data
        console.log(this.dyParams)
      } else if (this.activeName === 'only') {
        this.staticParmas = res.data
      }
    },

    // 监听标签页的改变获取不同的数据
    handleClick () {
      this.listenActiveName()
    },
    // 显示添加属性/参数对话框
    addDialog () {
      this.addDialogVisible = true
    },
    // 提交添加的属性
    submitAddForm () {
      this.$refs.addFormRef.validate().then(async () => {
        const { data: res } = await this.$http.post(
          `categories/${this.cateValue[this.cateValue.length - 1]}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('提交失败')
        }
        console.log(res.data)
        this.listenActiveName()
        this.addDialogVisible = false
        return this.$message.success('提交成功')
      })
    },
    // 关闭添加对话框 监听对话框关闭重置输入框
    closeAddDialog () {
      this.$refs.addFormRef.resetFields()
    },
    // 修改动态参数
    async editAdddyParmasForm (id) {
      this.editId = id
      const { data: res } = await this.$http.get(
        `categories/${
          this.cateValue[this.cateValue.length - 1]
        }/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }

      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改静态属性
    async editAddStaticForm (id) {
      this.editId = id
      const { data: res } = await this.$http.get(
        `categories/${
          this.cateValue[this.cateValue.length - 1]
        }/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }

      this.editForm = res.data
      this.editDialogVisible = true
    },

    // 提交修改属性
    submitEditForm () {
      this.$refs.editFormRef
        .validate()
        .then(async () => {
          const { data: res } = await this.$http.put(
            `categories/${
              this.cateValue[this.cateValue.length - 1]
            }/attributes/${this.editId}`,
            {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName.join(' ')
            }
          )

          if (res.meta.status !== 200) {
            return this.$message.error('修改失败')
          }
          this.editDialogVisible = false

          this.listenActiveName()
          return this.$message.success('修改成功')
        })
        .catch(() => {
          this.$message.error('修改失败')
        })
    },
    // 删除静态属性
    editDeleteStaticForm (id) {
      this.listenActiveName()
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${
              this.cateValue[this.cateValue.length - 1]
            }/attributes/${id}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.listenActiveName()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除静态属性
    editDeleteDyForm (id) {
      this.listenActiveName()
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${
              this.cateValue[this.cateValue.length - 1]
            }/attributes/${id}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.listenActiveName()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 当键盘按下是去焦点时触发
    async handleInputConfirm (row) {
      // 如果为空就返回标签不做处理
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return ''
      }
      // 如果不为空就做参数项处理
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      // 对增加的参数项做提交
      const { data: res } = await this.$http.put(
        `categories/${this.cateValue[this.cateValue.length - 1]}/attributes/${
          row.attr_id
        }`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      return this.$message.success('修改参数成功')
    },
    // 点击new-tag标签时变成输入框
    showInput (row) {
      row.inputVisible = true
      console.log(row.inputVisible)
    },
    // 删除参数项
    async deleteParamsItem (index, row) {
      // 删除从索引为index的数组 删除一个
      row.attr_vals.splice(index, 1)
      const { data: res } = await this.$http.delete(
        `categories/${this.cateValue[this.cateValue.length - 1]}/attributes/${
          row.attr_id
        }`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      return this.$message.success('修改参数成功')
    }
  },
  computed: {
    // 是否禁用的计算属性
    isButtonVisible () {
      if (this.cateValue.length === 3) {
        return false
      } else {
        return true
      }
    },
    // 判断是静态属性还是动态参数的对话框
    isDoalog () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
<style scoped>
.el-tag {
  margin: 10px 8px;
}
.input-new-tag {
  width: 100px;
}
</style>
